package bootstrap

import (
	"database/sql"
	"fmt"
	"xiehui-service/global"

	_ "github.com/alexbrainman/odbc"
	"go.uber.org/zap"
)

func InitializeMSACCESS() *sql.DB {
	// 根据驱动配置进行初始化
	switch global.App.Config.Msserver.Driver {
	case "access":
		return initSqlAccessGorm()
	default:
		return initSqlAccessGorm()
	}
}

// func getAccessGormLogger() logger.Interface {
// 	var logMode logger.LogLevel

// 	switch global.App.Config.Msaccess.LogMode {
// 	case "silent":
// 		logMode = logger.Silent
// 	case "error":
// 		logMode = logger.Error
// 	case "warn":
// 		logMode = logger.Warn
// 	case "info":
// 		logMode = logger.Info
// 	default:
// 		logMode = logger.Info
// 	}

// 	return logger.New(getAccessGormLogWriter(), logger.Config{
// 		SlowThreshold:             200 * time.Millisecond,                          // 慢 SQL 阈值
// 		LogLevel:                  logMode,                                         // 日志级别
// 		IgnoreRecordNotFoundError: false,                                           // 忽略ErrRecordNotFound（记录未找到）错误
// 		Colorful:                  !global.App.Config.Msaccess.EnableFileLogWriter, // 禁用彩色打印
// 	})
// }

// 自定义 gorm Writer
// func getAccessGormLogWriter() logger.Writer {
// 	var writer io.Writer

// 	// 是否启用日志文件
// 	if global.App.Config.Msaccess.EnableFileLogWriter {
// 		// 自定义 Writer
// 		writer = &lumberjack.Logger{
// 			Filename:   global.App.Config.Log.RootDir + "/" + global.App.Config.Msaccess.LogFilename,
// 			MaxSize:    global.App.Config.Log.MaxSize,
// 			MaxBackups: global.App.Config.Log.MaxBackups,
// 			MaxAge:     global.App.Config.Log.MaxAge,
// 			Compress:   global.App.Config.Log.Compress,
// 		}
// 	} else {
// 		// 默认 Writer
// 		writer = os.Stdout
// 	}
// 	return log.New(writer, "\r\n", log.LstdFlags)
// }

func initSqlAccessGorm() *sql.DB {
	dbConfig := global.App.Config.Msaccess
	if dbConfig.Database == "" {
		return nil
	}

	dbfilename := dbConfig.Host + dbConfig.Database
	db, err := sql.Open("odbc", fmt.Sprintf("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=%s;Uid=%s;Pwd=%s;", dbfilename, dbConfig.UserName, dbConfig.Password))
	if err != nil {
		global.App.Log.Info("access open failed==>>", zap.Any("原因", err))
		return nil
	}
	// defer db.Close()

	return db
}
